<!-- eslint-disable unused-imports/no-unused-vars -->
<script setup lang="ts">
import type { SummaryTask } from "../apis/type"
import { UploadFilled } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { computed, onMounted, reactive, ref } from "vue"
import {
  createOrUpdateSummaryApi,
  getStudentSummaryTasksApi,
  getSummaryTaskDetailApi,
  uploadAchievementFileApi
} from "../apis/report"

// 响应式数据
const loading = ref(false)
const taskList = ref<SummaryTask[]>([])
const dialogVisible = ref(false)
const reportFormRef = ref()
const currentTaskId = ref(0)
const currentTask = ref<SummaryTask>({
  id: 0,
  studentId: 0,
  studentName: "",
  positionId: 0,
  positionName: "",
  cycleType: "weekly",
  cycleName: "",
  startTime: "",
  endTime: "",
  deadline: "",
  remainingDays: 0,
  status: "pending"
})

// 判断是否逾期
const isOverdue = computed(() => currentTask.value.remainingDays < 0)

// 报告表单数据
const reportForm = reactive({
  taskId: 0,
  studentId: 1001, // 模拟学生ID
  workContents: [{ type: "", content: "" }],
  achievements: "",
  achievementFiles: [] as string[],
  problems: [{ problem: "", solution: "" }],
  nextPlan: "",
  remark: "",
  overdueReason: ""
})

// 成果附件列表
const achievementFileList = ref<any[]>([])

// 表单验证规则
const reportRules = {
  achievements: [
    { required: true, message: "请填写工作成果", trigger: "blur" }
  ],
  nextPlan: [
    { required: true, message: "请填写下周/月计划", trigger: "blur" }
  ],
  overdueReason: [
    { required: isOverdue.value, message: "请填写逾期理由", trigger: "blur" }
  ]
}

// 获取任务状态标签类型
function getTaskStatusType(status: string): "info" | "warning" | "success" | "danger" | "primary" {
  const statusMap: Record<string, "info" | "warning" | "success" | "danger" | "primary"> = {
    pending: "info",
    submitted: "warning",
    approved: "success",
    rejected: "danger"
  }
  return statusMap[status] || "info"
}

// 获取任务状态标签文本
function getTaskStatusLabel(status: string) {
  const statusMap: Record<string, string> = {
    pending: "待提交",
    submitted: "待审核",
    approved: "已通过",
    rejected: "已驳回"
  }
  return statusMap[status] || status
}

// 添加工作内容
function addWorkContent() {
  reportForm.workContents.push({ type: "", content: "" })
}

// 移除工作内容
function removeWorkContent(index: number) {
  reportForm.workContents.splice(index, 1)
}

// 添加问题与解决方法
function addProblemSolution() {
  reportForm.problems.push({ problem: "", solution: "" })
}

// 移除问题与解决方法
function removeProblemSolution(index: number) {
  reportForm.problems.splice(index, 1)
}

// 上传成果附件前校验
async function beforeUploadAchievement(file: File) {
  // 文件大小校验
  const maxSize = 5 * 1024 * 1024 // 5MB
  if (file.size > maxSize) {
    ElMessage.error("文件大小不能超过5MB")
    return false
  }

  // 文件类型校验
  const validTypes = [
    "application/pdf",
    "image/jpeg",
    "image/jpg",
    "image/png",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  ]
  const validExtensions = [".pdf", ".jpg", ".jpeg", ".png", ".xls", ".xlsx"]
  const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf("."))

  if (!validTypes.includes(file.type) && !validExtensions.includes(fileExtension)) {
    ElMessage.error("只支持PDF、JPG、PNG、Excel格式的文件")
    return false
  }

  // 上传文件
  try {
    const response = await uploadAchievementFileApi(file)
    if (response.code === 0) {
      reportForm.achievementFiles.push(response.data.url)
      achievementFileList.value.push({
        name: file.name,
        url: response.data.url,
        uid: Date.now()
      })
      ElMessage.success("上传成功")
    }
  } catch (_error) {
    ElMessage.error("上传失败")
  }

  return false // 阻止默认上传行为
}

// 加载任务列表
async function loadTaskList() {
  loading.value = true
  try {
    const { code, data } = await getStudentSummaryTasksApi()
    if (code === 200 && data) {
      taskList.value = data.list
    }
  } catch (error) {
    ElMessage.error("获取任务列表失败")
  } finally {
    loading.value = false
  }
}

// 处理提交报告
async function handleSubmitReport(taskId: number) {
  currentTaskId.value = taskId
  try {
    const { code, data } = await getSummaryTaskDetailApi(taskId)
    if (code === 200 && data) {
      currentTask.value = data
      reportForm.taskId = taskId
      dialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error("获取任务详情失败")
  }
}

// 处理查看报告
function handleViewReport(taskId: number) {
  // 这里可以实现查看报告详情的逻辑
  ElMessage.info("查看报告功能待实现")
}

// 提交报告
async function submitReport() {
  // 校验工作内容
  const hasEmptyWorkContent = reportForm.workContents.some(
    item => !item.type || !item.content.trim()
  )
  if (hasEmptyWorkContent) {
    ElMessage.error("请填写完整的工作内容")
    return
  }

  // 校验问题与解决方法
  const hasEmptyProblem = reportForm.problems.some(
    item => (item.problem || item.solution) && !(item.problem && item.solution)
  )
  if (hasEmptyProblem) {
    ElMessage.error("请填写完整的问题与解决方法")
    return
  }

  // 过滤空的问题项
  reportForm.problems = reportForm.problems.filter(
    item => item.problem || item.solution
  )

  try {
    await reportFormRef.value?.validate()

    loading.value = true
    const response = await createOrUpdateSummaryApi({
      ...reportForm,
      submittedAt: new Date().toISOString()
    })

    if (response.code === 200) {
      ElMessage.success("报告提交成功")
      dialogVisible.value = false
      loadTaskList() // 重新加载任务列表
      // 重置表单
      resetForm()
    }
  } catch (error) {
    ElMessage.error("报告提交失败")
  } finally {
    loading.value = false
  }
}

// 重置表单
function resetForm() {
  reportForm.workContents = [{ type: "", content: "" }]
  reportForm.achievements = ""
  reportForm.achievementFiles = []
  achievementFileList.value = []
  reportForm.problems = [{ problem: "", solution: "" }]
  reportForm.nextPlan = ""
  reportForm.remark = ""
  reportForm.overdueReason = ""
}

// 初始加载
onMounted(() => {
  loadTaskList()
})
</script>

<template>
  <div class="summary-report-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的总结任务</span>
        </div>
      </template>

      <!-- 任务列表 -->
      <div v-loading="loading" class="task-list">
        <el-table :data="taskList" style="width: 100%">
          <el-table-column prop="cycleName" label="周期" min-width="100" />
          <el-table-column prop="positionName" label="实习岗位" min-width="150" />
          <el-table-column prop="cycleType" label="类型" min-width="80">
            <template #default="scope">
              <el-tag :type="scope.row.cycleType === 'weekly' ? 'primary' : 'success'">
                {{ scope.row.cycleType === 'weekly' ? '周报' : '月报' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deadline" label="截止时间" min-width="150" />
          <el-table-column prop="remainingDays" label="剩余天数" min-width="100">
            <template #default="scope">
              <el-tag :type="scope.row.remainingDays < 3 ? 'danger' : 'warning'" v-if="scope.row.remainingDays >= 0">
                {{ scope.row.remainingDays }}天
              </el-tag>
              <el-tag type="danger" v-else>
                已逾期{{ Math.abs(scope.row.remainingDays) }}天
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" min-width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 'pending'" type="info">
                待提交
              </el-tag>
              <el-tag v-else-if="scope.row.status === 'submitted'" type="warning">
                待审核
              </el-tag>
              <el-tag v-else-if="scope.row.status === 'approved'" type="success">
                已通过
              </el-tag>
              <el-tag v-else-if="scope.row.status === 'rejected'" type="danger">
                已驳回
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="120" fixed="right">
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 'pending' || scope.row.status === 'rejected'"
                type="primary"
                size="small"
                @click="handleSubmitReport(scope.row.id)"
              >
                提交报告
              </el-button>
              <el-button
                v-else
                type="info"
                size="small"
                @click="handleViewReport(scope.row.id)"
              >
                查看报告
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 提交报告对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="提交总结报告"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="reportFormRef"
        :model="reportForm"
        :rules="reportRules"
        label-width="100px"
      >
        <!-- 周期信息 -->
        <el-form-item label="周期信息">
          <el-descriptions border :column="2" :model="currentTask" size="small">
            <el-descriptions-item label="周期名称">
              {{ currentTask.cycleName }}
            </el-descriptions-item>
            <el-descriptions-item label="截止时间">
              {{ currentTask.deadline }}
            </el-descriptions-item>
            <el-descriptions-item label="实习岗位">
              {{ currentTask.positionName }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getTaskStatusType(currentTask.status)">
                {{ getTaskStatusLabel(currentTask.status) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-form-item>

        <!-- 工作内容 -->
        <el-form-item label="工作内容" required>
          <div v-for="(item, index) in reportForm.workContents" :key="index" class="work-content-item">
            <el-row :gutter="10">
              <el-col :span="8">
                <el-select v-model="item.type" placeholder="选择工作类型" style="width: 100%">
                  <el-option label="协助开发" value="协助开发" />
                  <el-option label="数据整理" value="数据整理" />
                  <el-option label="文档编写" value="文档编写" />
                  <el-option label="测试" value="测试" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-col>
              <el-col :span="15">
                <el-input
                  v-model="item.content"
                  placeholder="具体工作内容（如：完成3个接口编写）"
                  type="textarea"
                  :rows="2"
                />
              </el-col>
              <el-col :span="1">
                <el-button
                  v-if="reportForm.workContents.length > 1"
                  type="danger"
                  icon="Delete"
                  @click="removeWorkContent(index)"
                  circle
                  size="small"
                />
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" icon="Plus" @click="addWorkContent" plain size="small">
            添加工作内容
          </el-button>
        </el-form-item>

        <!-- 工作成果 -->
        <el-form-item label="工作成果" prop="achievements" required>
          <el-input
            v-model="reportForm.achievements"
            placeholder="量化描述工作成果（如：完成2份数据分析报告）"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <!-- 成果附件 -->
        <el-form-item label="成果附件">
          <el-upload
            v-model:file-list="achievementFileList"
            :before-upload="beforeUploadAchievement"
            :auto-upload="false"
            :limit="3"
            accept=".pdf,.jpg,.jpeg,.png,.xls,.xlsx"
            drag
          >
            <el-icon class="el-icon--upload">
              <UploadFilled />
            </el-icon>
            <div class="el-upload__text">
              点击或拖拽文件到此区域上传
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持PDF/JPG/PNG/Excel格式，单个文件大小不超过5MB，最多上传3个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 问题与解决方法 -->
        <el-form-item label="问题与解决方法">
          <div v-for="(item, index) in reportForm.problems" :key="index" class="problem-solution-item">
            <el-row :gutter="10">
              <el-col :span="24">
                <el-input
                  v-model="item.problem"
                  placeholder="遇到的问题（如：对XX工具不熟悉）"
                  type="textarea"
                  :rows="2"
                />
              </el-col>
              <el-col :span="24">
                <el-input
                  v-model="item.solution"
                  placeholder="问题解决方法（如：学习B站教程掌握工具）"
                  type="textarea"
                  :rows="2"
                />
              </el-col>
              <el-col :span="24" style="text-align: right; margin-top: 5px;">
                <el-button
                  v-if="reportForm.problems.length > 1"
                  type="danger"
                  icon="Delete"
                  @click="removeProblemSolution(index)"
                  plain
                  size="small"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" icon="Plus" @click="addProblemSolution" plain size="small">
            添加问题与解决方法
          </el-button>
        </el-form-item>

        <!-- 下周/月计划 -->
        <el-form-item label="下周/月计划" prop="nextPlan" required>
          <el-input
            v-model="reportForm.nextPlan"
            placeholder="与工作衔接的计划（如：完成XX模块开发）"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input
            v-model="reportForm.remark"
            placeholder="可选，如：本周停电2天，已补班"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <!-- 逾期理由 -->
        <el-form-item
          v-if="isOverdue"
          label="逾期理由"
          prop="overdueReason"
          required
        >
          <el-input
            v-model="reportForm.overdueReason"
            placeholder="请说明逾期提交的原因"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitReport">
          提交报告
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.summary-report-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.work-content-item,
.problem-solution-item {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.work-content-item:last-child,
.problem-solution-item:last-child {
  margin-bottom: 0;
}

.el-upload {
  margin-top: 10px;
}
</style>
